// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.

// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".

// import socket from "./socket"
import "jquery"
import "simplelightbox"

var House = {}

function get_gps() {
  if (window.SwiftWebViewBridge) {
    SwiftWebViewBridge.sendDataToSwift({ 'cmd' : 'gps' })
  }
}

function select_address($item) {
  var index = $item.data("index")
  var pois = House.message.pois
  var [name, address] = pois[index].split("||")
  $("#item_name").val(name)
  $("#item_address").val(address)
  $(".address-select-c").removeClass("in").addClass("collapse")
}

function update_gps(message) {
  House.message = message
  var gps = message.gps
  var arr = [
    gps.latitude.toFixed(2),
    gps.longitude.toFixed(2)
  ]
  $("#item_gps").val(arr.join(","))
  var pois = message.pois
  var htmls = []
  for (var i = 0; i < pois.length; i++) {
    var poi = pois[i].split("||")
    htmls.push([
      "<li class='address-item' data-index='"+i+"'>",
      "<div class='title'>",
      poi[0],
      "</div>",
      "<div class='address'>",
      poi[1],
      "</div>",
      "</li>"
    ].join(""))
  }
  $(".address-select-c").html(htmls.join("")).removeClass("collapse").addClass("in")

  var html = $(".get-gps").html()
  $(".get-gps").data("data-text", html).html($(".get-gps").data("default-text"))
}

function make_bridge() {
  if (window.SwiftWebViewBridge) {
    SwiftWebViewBridge.init(function(message, responseCallback) {
      var cmd = message.cmd
      if (cmd) {
        if (cmd == 'gps') {
          update_gps(message)
        }
      }
    })
  } else {
    setTimeout(function() {
      make_bridge()
    }, 1000);
  }
}

$(function ready() {
  make_bridge()
  $(".get-gps").click(function(){
    var html = $(this).html()
    $(this).data("default-text", html).html($(this).data("loading-text"))
    get_gps()
  })
  $(document).on("click", ".address-item", function(){
    select_address($(this))
  })

  $('[data-toggle="collapse"]').click(function(){
    $($(this).data("target")).toggle();
  })

  var gallery = $('.photos a.photo').simpleLightbox();
})

